package com.cheyun.netsalev3.viewmodel

import android.content.Context
import android.content.Intent
import android.os.Looper
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.ObservableField
import androidx.lifecycle.MutableLiveData
import com.cheyun.netsalev3.MyApplication
import com.cheyun.netsalev3.R
import com.cheyun.netsalev3.bean.*
import com.cheyun.netsalev3.bean.basedata.Customerlevel
import com.cheyun.netsalev3.bean.basedata.Member
import com.cheyun.netsalev3.bean.drive.DriveListInfo
import com.cheyun.netsalev3.bean.login.PhoneX
import com.cheyun.netsalev3.bean.records.*
import com.cheyun.netsalev3.repository.ClueDetailsRepository
import com.cheyun.netsalev3.repository.CueTransferActivityRepository
import com.cheyun.netsalev3.utils.*
import com.cheyun.netsalev3.view.*
import com.cheyun.netsalev3.view.cluefollowup.ClueFollowUpActivity
import com.cheyun.netsalev3.widget.CallPopFragment
import com.cheyun.netsalev3.widget.MyContentDialog
import com.cheyun.netsalev3.widget.MyDialog
import com.cheyun.netsalev3.widget.PopDialog
import com.dou361.dialogui.DialogUIUtils
import com.dou361.dialogui.listener.DialogUIItemListener
import com.jeremyliao.liveeventbus.LiveEventBus
import java.io.Serializable
import java.util.*
import kotlin.collections.ArrayList

class ClueDetailsActivityViewModel(var clueDetailsRepository: ClueDetailsRepository,var come:String,var keliudata: Data?,
                                   var revkey:String) : BaseViewModel(), PopDialog.PopDialogListener {
    var clueDetails = ObservableField<ClueDetails>()
    var recordsParam = RecordsParam()
    //历史纪录
    var recordsList = MutableLiveData<List<Follow>>()
    //底部按钮
    var bottomList = MutableLiveData<List<NameIdParam>>()

    var clueRow = MutableLiveData<Row>()

    var nkey = MutableLiveData<String>()
    var recordVoice = MutableLiveData<String>()
    var sex = MutableLiveData<String>()
    var phoneMsg = MutableLiveData<String>()

    var showIsarrive = ObservableField<Boolean>(false)

    //到店，线索移交相关
    //用户级别
    var customerlevel = MySharedPreferences.getBaseData()?.customerlevel
    var customerlevelName = ObservableField<String>("")
    var customerlevelPosition = -1
    //移交用户
    var member = MutableLiveData<List<NameIdParam>>()
    var memberName = ObservableField<String>("")
    var memberId = ""
    private var dialog: PopDialog? = null

    var hasLoadHistory = false
    var goFollowUpListActivity = false
    var v:View? = null
    //用户标签
    var userTag = MutableLiveData<List<DialogParam>>()
    var loginData = MySharedPreferences.getLoginData()

    /**
     * 初始化数据
     */
    fun initData(s: String) {
        clueDetailsRepository.getData(this::setData)
        if (!s.isNullOrBlank()) {
            MyToast(s)
        }
    }

    init {
        initData("")
    }

    fun refreshDetail(){
        clueDetailsRepository.getData(this::setData)
//        if(hasLoadHistory){
////            loadRecord()
////        }
        loadRecord()
    }

    private fun setData(item: ClueDetails, nkey: String) {
        var us = arrayListOf<DialogParam>()
        if(item.alllabels!=null){
            for(it in item.alllabels){
                us.add(DialogParam(it.title,it.id.toString(), if(it.rttype == 1)"1" else "0"))
            }
            userTag.postValue(us)
        }
        var isadmin = loginData?.member?.isadmin ?: 0
        if (isadmin == 1) {
            if(item.drivingisarrive == 1){
                showIsarrive.set(true)
            }
        } else {
            loginData?.member?.apps?.chance?.apply {
                for (i in this) {
                    when (i) {
                        "9003" -> {
                            if(item.drivingisarrive == 1){
                                showIsarrive.set(true)
                            }
                        }
                    }
                }
            }
        }

        this.recordVoice.postValue(item.recordVoice)
        LiveEventBus.get().with("clueupdatgemingxi").postValue(item)
        LiveEventBus.get().with("cluebuyingmingxi").postValue(item)
        this.nkey.postValue(nkey)
        item.getData()
        clueDetails.set(item)
        this.sex.postValue(item.sex.toString())
//        跟进：archive.purge 1
//        订车：archive.order 5
//        提车：archive.thenend 10
//        战败：archivecheck.fail 32
//       "archivepot.index", "archivepot.discard", "archivepot.failure", "archivepot.invalid"
        var temlist = ArrayList<NameIdParam>()
        var needJihuo:Boolean = false
        if(!revkey.isNullOrEmpty() && (item.state.equals("21") || item.state.equals("22") || item.state.equals("23")|| item.state.equals("24")) ){
            needJihuo = true
        }
        if(item.state.equals("31") || item.state.equals("32") || item.state.equals("33") || needJihuo){
            temlist.add(NameIdParam("拨号", "0", R.drawable.a03_2_1_ddkhxq_call))
            temlist.add(NameIdParam("激活", "0", R.drawable.b01_1_1_qkxq_activation))
        }else{
            when (nkey) {
                "archive.purge", "archive.order", "archive.thenend", "archive.index" -> {
                    var hasOD = false
                    for (i in item.levelList) {
                        if(i.ikey.equals("O")|| i.ikey.equals("D")){
                            hasOD = true
                        }
                    }
                    // 2021-2-25 对是否有预约进行判断  有： 跟进、取消试驾、分配
                    if(!item.reserveid.equals("0")){
                        temlist.add(NameIdParam("跟进", "0", R.drawable.a01_1_1_zbxq_followup))
                        temlist.add(NameIdParam("取消试驾", "0", R.drawable.qxsj_tb))
                    }else{
                        if(item.Level == "D"){
                            temlist.add(NameIdParam("回访", "0", R.drawable.hf_tb))
                        }else{
                            temlist.add(NameIdParam("跟进", "0", R.drawable.a01_1_1_zbxq_followup))

                            if (item.Level != "O" && item.Level != "D") {
                                if(hasOD) {
                                    temlist.add(NameIdParam("订车", "1", R.drawable.a02_2_xsxq_order))
                                }
                            }
                            if(item.Level == "D" || item.Level == "O"){
                                //长马没有提车环节
//                            if(hasOD) {
//                                temlist.add(NameIdParam("提车", 1, R.drawable.a02_2_xsxq_order))
//                            }
                            }
                        }

                        var hasF = false
                        for (i in item.levelList) {
                            if(i.ikey.equals("F") && item.effective.equals("1")){
                                hasF = true
                            }
                        }
                        //有VIN信息，不能再进行战败
                        if(!item.vin.isNullOrEmpty()){
                            hasF = false
                        }
                        if(hasF){
                            temlist.add(NameIdParam("战败", "2", R.drawable.a01_1_1_zbxq_falsedefeat))
                        }
                    }

                    if(MySharedPreferences.getLoginData()?.member?.isadmin == 1){
                        temlist.add(NameIdParam("分配", "3", R.drawable.a02_2_xsxq_handover))
                    }else{
                        MySharedPreferences.getLoginData()?.member?.apps?.chance?.apply {
                            for (i in this) {
                                if ( i.equals("9003")) {
                                    temlist.add(NameIdParam("分配", "3", R.drawable.a02_2_xsxq_handover))
                                }
                            }
                        }
                    }
                }
                "archivecheck.fail" -> {
                    temlist.add(NameIdParam("跟进", "0", R.drawable.a01_1_1_zbxq_followup))
                    temlist.add(NameIdParam("确认战败", "0", R.drawable.a01_1_1_zbxq_comfiredefeat))
                    temlist.add(NameIdParam("虚假战败", "0", R.drawable.a01_1_1_zbxq_falsedefeat))
                }
                "archivecheck.invalid" -> {
                    temlist.add(NameIdParam("跟进", "0", R.drawable.a01_1_1_zbxq_followup))
                    temlist.add(NameIdParam("确认无效", "0", R.drawable.a01_1_1_zbxq_comfiredefeat))
                    temlist.add(NameIdParam("虚假无效", "0", R.drawable.a01_1_1_zbxq_falsedefeat))
                }
                "archivepot.index", "archivepot.discard", "archivepot.failure", "archivepot.invalid" -> {
                    temlist.add(NameIdParam("拨号", "0", R.drawable.a03_2_1_ddkhxq_call))
                    temlist.add(NameIdParam("激活", "0", R.drawable.b01_1_1_qkxq_activation))
                }
            }
        }
        bottomList.postValue(temlist)
        phoneMsg.postValue(item.phone)

        var row = Row(
                item.brand.toInt(),
                item.channel.toInt(),
                item.customerlevel.toInt(),
                item.customerlevelname,
                item.dateline,
                item.posttime,
                item.followname,
                item.exterior.toInt(),
                item.exteriorname,
                item.infoplace.toInt(),
                item.infoplacename,
                item.infosource.toInt(),
                item.infosourcename,
                item.infotype.toInt(),
                item.infotypename,item.interior.toInt(),item.interiorname,item.phone,item.region,
                item.series.toInt(),item.seriesname,item.brandname,item.sex.toInt(),item.spec.toInt(),item.specname,item.tid,
                0,item.uname,item.state,item.price,item.lastpost,item.ownername,item.hot.toInt(),item.xphone
        )
        row.setData(0,nkey,true)
        clueRow.postValue(row)
    }

    fun loadRecord(goFollow:Boolean = false){
        hasLoadHistory = true
        goFollowUpListActivity = goFollow

        clueDetailsRepository.getRecords(clueDetailsRepository?.tid.toString(), this::setRecords)
//        if(clueDetails.get()==null){
//            clueDetailsRepository.getRecords(clueDetailsRepository.tid.toString(), this::setRecords)
//        }else{
//            clueDetailsRepository.getRecords(clueDetails.get()?.tid!!, this::setRecords)
//        }

    }
    /**
     * 线索记录回调
     */
    fun setRecords(recordsParam: List<Follow>) {

        var temlist = ArrayList<Any>()
        for(record in recordsParam){

            if(record.type.equals("transfer")){
                record.typeName = "流转"
                record.typeId = 1
            }else if(record.type.equals("follow")){
                record.typeName = "跟进"
                record.typeId = 3
            }else if(record.type.equals("touch")){
                record.typeName = "触达"
                record.typeId = 2
            }else if(record.type.equals("reserve")){
                record.typeName = "试驾"
                record.typeId = 4
            }else if(record.type.equals("call")){
                record.typeName = "通话"
                record.typeId = 5
                record.call_info.calltype_name =  if(record.call_info.calltype.equals("1")) "来电" else "去电"
            }else if(record.type.equals("deal")){
                record.typeName = "成交"
                record.typeId = 6
            }else if(record.type.equals("failure")){
                record.typeName = "战败"
                record.typeId = 7
            }else if(record.type.equals("failure")){
                record.typeName = "战败"
                record.typeId = 7
            }else if(record.type.equals("receive")){
                record.typeName = "到店"
                record.typeId = 8
            }else if(record.type.equals("invite")){
                record.typeName = "邀约"
                record.typeId = 9
            }else if(record.type.equals("create")){
                record.typeName = "建档"
                record.typeId = 10
            }else if(record.type.equals("handover")){
                record.typeName = "移交"
                record.typeId = 11
            }
        }
//        temlist.addAll(recordsParam.follow)
//        temlist.addAll(recordsParam.transfer)
//        temlist.addAll(recordsParam.call)
//        temlist.addAll(recordsParam.touch)
//        temlist.addAll(recordsParam.purchase)
//        temlist.addAll(recordsParam.reserve)

        //排序
//        Collections.sort(temlist, RecordsComparator())
//        Log.e("LogInterceptor", temlist.toString())
        recordsList.postValue(recordsParam)

//        if(goFollowUpListActivity){
//            if(recordsParam.follow != null) {
//                //transfer表示流转记录；键follow表示跟进记录，键call表示通话记录
//                var intent = Intent(v?.context, FollowUpListActivity::class.java)
//                intent.putExtra("data", recordsParam.follow as Serializable)
//                v?.context!!.startActivity(intent)
//            }
//        }

    }


    /**
     * 点击更多跟进
     */
    fun onClickMorFollowup(view: View) {
        v = view
        if(!hasLoadHistory){
            loadRecord(true)
        }else{
            if(recordsParam.follow != null) {
                //transfer表示流转记录；键follow表示跟进记录，键call表示通话记录
                var intent = Intent(view.context, FollowUpListActivity::class.java)
                intent.putExtra("data", recordsParam.follow as Serializable)
                view.context.startActivity(intent)
            }
        }
    }

    /**
     * 点击更多购车记录
     */
    fun onClickMorBuyCar(view: View) {
        //transfer表示流转记录；键follow表示跟进记录，键call表示通话记录
        if(clueDetails.get() != null){
            var intent = Intent(view.context, CarBuyDetailsActivity::class.java)
            intent.putExtra("data", clueDetails.get() as Serializable)
            view.context.startActivity(intent)
        }
    }

    /**
     * 点击更多订车记录
     */
    fun onClickMorLiftCar(view: View) {
        if(clueDetails.get() != null) {
            //transfer表示流转记录；键follow表示跟进记录，键call表示通话记录
            var intent = Intent(view.context, CarBuyDetailsActivity::class.java)
            intent.putExtra("data", clueDetails.get() as Serializable)
            intent.putExtra("tiCar", true)
            view.context.startActivity(intent)
        }
    }

    /**
     * 点击更多试驾记录
     */
    fun onClickMorDrive(view: View) {
        if(recordsParam.reserve != null) {
            //transfer表示流转记录；follow表示跟进记录，call表示通话记录 , reserve表示试驾记录
            var intent = Intent(view.context, CarDriveDetailsActivity::class.java)
            intent.putExtra("data", recordsParam.reserve as Serializable)
            view.context.startActivity(intent)
        }
    }

    /**
     * 点击头部右边
     */
    fun onClickRight(view: View) {
        clueDetails.get()?.apply {
            var intent = Intent(view.context, ClueDetailMingXiActivity::class.java)
            intent.putExtra("data", clueDetails.get() as Serializable)
            intent.putExtra("follow", recordsParam.follow as Serializable)
            view.context.startActivity(intent)
        }
    }


    /**
     * 点击底部按钮
     */
    fun onClickBottom(view: View, item: NameIdParam) {
        bottomItem = item
        when (item.name) {
            "跟进" -> Genjin(view, "",false)
            "订车" -> Genjin(view, "O",false)
            "提车" -> Genjin(view, "D",false)
            "战败" -> Genjin(view, "F",false)
            "分配" -> yiJiao(view)
//            "移交" -> yiJiao(view)
            "确认无效" -> invalid(view)
            "确认战败" -> Defeat(view)
            "虚假战败" -> XdefeatInvalid(view, item.name)
            "虚假无效" -> XdefeatInvalid(view, item.name)
            "激活" -> XdefeatInvalid(view, item.name)
            "拨号" -> {
//                clueDetails.get()?.phone?.apply {
//                    FunctionUtils.callPhone(view.context, this)
//                }
                onClickPhone(view)
            }
            "回访" -> Genjin(view, "D",true)
            "退车" -> Genjin(view, "O",true)
            "取消试驾" -> Genjin(view, "",false,1)
        }
    }

    //底部按钮
    var bottomItem = NameIdParam("", "-1")
    var levellist = ArrayList<Customerlevel>()
    var memberlist = ArrayList<Member>()
    var memberitem: DialogParam? = null
    var context: AppCompatActivity? = null

    init {
        MySharedPreferences.getBaseData()?.customerlevel?.apply {
            levellist.addAll(this)
        }
        MySharedPreferences.getBaseData()?.member?.apply {
            memberlist.addAll(this)
        }
    }

    /**
     * 虚假无效 虚假战败
     */
    private fun XdefeatInvalid(view: View, name: String) {
        var temcontext = view.context
        if (temcontext is AppCompatActivity) {
            context = temcontext
            var hasTranslate = false
            if(MySharedPreferences.getLoginData()?.member?.isadmin == 1){
                hasTranslate = true
            }else{
                MySharedPreferences.getLoginData()?.member?.apps?.chance?.apply {
                    for (i in this) {
                        if ( i.equals("9003")) {
                            hasTranslate = true
                        }
                    }
                }
            }
            if(hasTranslate){
                memberitem = null
                var temlist = ArrayList<DialogParam>()
                for (i in memberlist) {
                    var item = DialogParam(i.realname, i.uid.toString())
                    temlist.add(item)
                }

                var pop = MyDialog.newInstance("选择线索接收者", temlist)
                pop.huidia = this::huidiao
                pop.show(temcontext.supportFragmentManager, "")
            }else{
                //默认自己， 默认N级
                var owneruid = ""
                var customerlevel = ""

                for (i in memberlist) {
                    var item = DialogParam(i.realname, i.uid.toString())
                    if(i.mobile.equals(MySharedPreferences.getMobile())){
                        owneruid = i.uid.toString()
                    }
                }
                for (i in levellist) {
                    if(i.ikey.equals("N")){
                        customerlevel = i.id.toString()
                    }
                }
                clueDetails.get()?.apply {
                    clueDetailsRepository.getActivate(this.tid.toString(),this@ClueDetailsActivityViewModel::setActivate, owneruid, customerlevel)
                }
            }
        }
    }

    /**
     * 选中用户回调
     */
    fun huidiao(item: DialogParam?) {
        if (item == null) {
            MyToast("请选择数据转入者")
            return
        }
        memberitem = item
        context?.apply {
            var temlist = ArrayList<DialogParam>()
            for (i in levellist) {
                var state = clueDetails.get()?.state
                var needJihuo:Boolean = false
                if(!revkey.isNullOrEmpty() && (state.equals("21") || state.equals("22") || state.equals("23")|| state.equals("24")) ){
                    needJihuo = true
                }
                if(state.equals("31") || state.equals("32") || state.equals("33") || needJihuo){
                    if(i.ikey.equals("o",true) || i.ikey.equals("d",true) || i.ikey.equals("f",true)){
                        continue
                    }
                }
                var item = DialogParam(i.title, i.id.toString())
                item.ikey = i.ikey
                temlist.add(item)
            }

            var pop = MyDialog.newInstance("选择客户级别", temlist)
            pop.huidia = this@ClueDetailsActivityViewModel::huidiao2
            pop.show(supportFragmentManager, "")
        }
    }

    /**
     * 选中等级回调
     */
    fun huidiao2(item: DialogParam?) {
        if (item == null) {
            MyToast("请选择客户级别")
            return
        }
        clueDetails.get()?.apply {
            when (bottomItem.name) {
                "虚假战败" -> clueDetailsRepository.getfailVerify(this.tid.toString(), "2",
                        this@ClueDetailsActivityViewModel::resultBack, memberitem?.id.toString(), item?.id.toString())
                "虚假无效" -> clueDetailsRepository.getInvalidVerify(this.tid.toString(), "2",
                        this@ClueDetailsActivityViewModel::resultBack, memberitem?.id.toString(), item?.id.toString())
                "激活" -> clueDetailsRepository.getActivate(this.tid.toString(),
                        this@ClueDetailsActivityViewModel::setActivate, memberitem?.id.toString(), item?.id.toString())
            }
        }
    }

    /**
     * 激活回调
     */
    fun setActivate(s: String) {
//        context?.apply {
//            var intent = Intent(this, SneakGuestListActivity::class.java)
//            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
//            startActivity(intent)
//        }
        clueDetailsRepository?.nkey = "archive.purge"
        LiveEventBus.get().with("clueupdatge").postValue("")
        MyToast(s)
    }

    /**
     * 确认战败
     */
    private fun Defeat(view: View) {

        var context = view.context
        if (context is AppCompatActivity) {
            var pop = MyContentDialog.newInstance("提示", "确认战败？")
            pop.onClickOk = this::onClickDefeatOk
            pop.show(context.supportFragmentManager, "")
        }
    }

    /**
     * 确认无效
     */
    private fun invalid(view: View) {
        var context = view.context
        if (context is AppCompatActivity) {
            var pop = MyContentDialog.newInstance("提示", "确认无效？")
            pop.onClickOk = this::onClickOk
            pop.show(context.supportFragmentManager, "")
        }
    }

    /**
     * 无效回调
     */
    fun onClickOk() {
        clueDetails.get()?.apply {
            clueDetailsRepository.getInvalidVerify(this.tid.toString(), "1",this@ClueDetailsActivityViewModel::resultBack)
        }
    }

    /**
     * 战败回调
     */
    fun onClickDefeatOk() {
        clueDetails.get()?.apply {
            clueDetailsRepository.getfailVerify(this.tid.toString(), "1", this@ClueDetailsActivityViewModel::resultBack)
        }
    }

    /**
     * 线索移交
     */
    private fun yiJiao(view: View) {
        var intent = Intent(view.context, CueTransferActivity::class.java)
        intent.putExtra("nkey", clueDetailsRepository.nkey)
        intent.putExtra("ids", clueDetails.get()?.tid)
        intent.putExtra("level", clueDetails.get()?.Level)
        view.context.startActivity(intent)
    }

    var statkun = 0

    init {
        MySharedPreferences.getLoginData()?.channel?.settings?.storage?.state?.apply {
            statkun = this
        }
    }

    /**
     * 跟进
     */
    fun Genjin(view: View, leve: String,levelLock:Boolean,canceldrive:Int = 0) {
        if (leve == "D") {
            clueDetails.get()?.apply {
                if (statkun == 1 && vin == "" && !clueDetails.get()?.Level.equals("D")) {
                    Toast.makeText(MyApplication.getInstance(), "请等待分配库存", Toast.LENGTH_LONG).show()
                    return
                }
            }
        }

        var intent = Intent(view.context, ClueFollowUpActivity::class.java)
        intent.putExtra("data", clueDetails.get() as Serializable)

        if(!clueDetails.get()?.vin.isNullOrEmpty()){
            intent.putExtra("leve", clueDetails.get()?.Level!!)
            intent.putExtra("levelLock", true)
        }else{
            var level = leve
            if(level.isEmpty()){
                if(clueDetails.get()?.Level!!.isNotEmpty()){
                    level = clueDetails.get()?.Level!!
                }
            }
            intent.putExtra("leve", level)
            intent.putExtra("levelLock", levelLock)
        }

        intent.putExtra("come", come)
        if(!clueDetails.get()?.reserveid.equals("0")){
            intent.putExtra("canceldrive", canceldrive)
        }

        if(keliudata!=null)
            intent.putExtra("keliudata", keliudata!! as Serializable)
        view.context.startActivity(intent)
    }

    /**
     * 点击到店记录
     */
    fun arriveView(view: View, item: Follow) {
        item.show = !item.show
    }

    /**
     * 点击到购车记录
     */
    fun purchaseView(view: View, item: PurchaseInfo) {
        item.show = !item.show
    }

    /**
     *点击通话记录
     */
    fun callPhone(view: View, item: Follow) {
        if (item.call_info.record.isNullOrBlank()) {
            Toast.makeText(view.context, "无法播放", Toast.LENGTH_LONG).show()
            return
        }

        var context = view.context
        if (context is AppCompatActivity) {
            var pop = CallPopFragment.newInstance(item.call_info.record,  if(item.call_info.calltime == null) "--" else item.call_info.calltime, item.call_info.times)
            pop.show(context.supportFragmentManager, "")
        }
    }

    fun clickRecordDetail(view: View, item: CallParam){
        var intent = Intent(view.context, H5Activity::class.java)
        intent.putExtra("url",item.recordDetail)
        view.context.startActivity(intent)
    }

    /**
     * 点击试驾记录
     */
    fun showDriveView(view: View, item: Follow) {
        item.show = !item.show
    }

    fun resultBack(msg:String,result:Int){
        if (!msg.isNullOrBlank()) {
            MyToast(msg)
        }
        LiveEventBus.get().with("to_audit").postValue("")
        myFinish(result)
    }

    fun setPhoneList(phoneList: List<PhoneX>) {
        val strings = ArrayList<String>()
        phoneList.forEach{strings.add("["+it.supusename+"]" + it.phonex)}
        if(phoneList.size>0){
            Looper.prepare()
            DialogUIUtils.showBottomSheetAndCancel(currentView?.context,strings,"取消",object: DialogUIItemListener(){
                override fun onItemClick(text: CharSequence, position: Int) {
                    var current = phoneList.get(position)
                    if(current.phonex.equals(MySharedPreferences.getMobile())){
                        FunctionUtils.callPhone(currentView?.context!!, clueDetails?.get()?.phone!!)
                    }else{
                        var enableBenji:Boolean = false
                        if(clueDetails?.get()?.phone!!.indexOf("*")==-1){
                            enableBenji = true
                        }
                        getPrivacyPhone(current.phonex!!,if(enableBenji) clueDetails?.get()?.phone!! else "",if(enableBenji) "" else clueDetails?.get()?.tid.toString(), currentView?.context!!)
                    }
                }
            }).show()
            Looper.loop()
        }else{
            ToastUtil.toastShortMessage("无工作号，暂时无法呼叫")
        }
    }
    private var currentView:View? = null

    fun onClickPhone(view: View) {
        currentView = view
        clueDetails.get()?.apply {
            var phone = this.phone
            if(phone.isNullOrEmpty()){
                ToastUtil.toastShortMessage("线索号码无法拨打")
            }else{
                clueDetailsRepository.getOwnerPhone(phone,this@ClueDetailsActivityViewModel::setPhoneList)

            }
        }
    }

    var mContext: Context? = null
    fun getPrivacyPhone(phonex:String,phoneb:String,tid:String,context: Context){
        this.mContext = context
        clueDetailsRepository.getPrivacyPhone(phonex,phoneb,tid,this@ClueDetailsActivityViewModel::setPrivacyPhone)
    }

    fun setPrivacyPhone(s: String) {
        FunctionUtils.callPhone(mContext!!, s)
    }

    fun onCallTel(view:View){
        if (clueDetails.get()?.phone?.indexOf("*") == -1) {
            FunctionUtils.callPhone(view.context, clueDetails.get()?.phone!!)
        } else {
            com.cheyunkeji.er.utils.ToastUtil.showToast("当前号码不能拨打")
        }
    }

    fun onToWeixin(view:View){
        if (clueDetails.get()?.phone?.indexOf("*") == -1) {
            CommonFunc.copy(view.context, clueDetails.get()?.phone!!)
            com.cheyunkeji.er.utils.ToastUtil.showToast("复制成功")
        } else {
            com.cheyunkeji.er.utils.ToastUtil.showToast("当前号码不能复制")
        }
        FunctionUtils.startAppWithPackageName(view.context,"com.tencent.mm")
    }
    fun onSetFocus(view:View){
        var moth: () -> Unit = {
            if (clueDetails.get()?.isfocus == 1) {
                clueDetails.get()?.isfocus = 0
                com.cheyunkeji.er.utils.ToastUtil.toastShortMessage("已取消标记为重点客户")
            } else {
                clueDetails.get()?.isfocus = 1
                com.cheyunkeji.er.utils.ToastUtil.toastShortMessage("已标记为重点客户")
            }
            LiveEventBus.get().with("CustomerItemFragmentSingle").postValue(clueDetails.get())
        }
        clueDetailsRepository.setIsFocus(clueDetails.get()?.tid.toString(),clueDetails.get()?.isfocus!!,moth)
    }
    fun onClickFollow(view:View){
        var content = view.context
        if (content is AppCompatActivity) {
            var intent = Intent(view.context, EditClubActivity::class.java)
            intent.putExtra("data", clueDetails.get() as Serializable)
            view.context.startActivity(intent)
        }

    }
    fun onClickDriver(view:View){
        var content = view.context
        if (content is AppCompatActivity) {
            var intent = Intent(view.context, AddDriveActivity::class.java)
            var driveInfo = DriveListInfo("","","",
                    "","","",
                    0,"",clueDetails.get()?.phone!!,
                    "","","",
                    "","","",
                    "","","",
                    0,"",clueDetails.get()?.tid.toString(),
                    clueDetails.get()?.uname!!,0,0,
                    "","","",
                    "","","","","","", arrayListOf(),"","")
            intent.putExtra("data", driveInfo as Serializable)
            view.context.startActivity(intent)
        }
    }

    fun memberInit(){
        var memberList = MySharedPreferences.getBaseData()?.member
        var dealerId = MySharedPreferences.getLoginData()?.member?.dealerid!!
        var check = false
        if(MySharedPreferences.getLoginData()?.channel?.isgroup.equals("1") && MySharedPreferences.getLoginData()?.member?.dealerid!=0){
            check = true
        }
        var ls = arrayListOf<NameIdParam>()

        memberList?.apply {
            for (it in this) {
                if(check){
                    if(it.dealerid == dealerId){
                        ls.add(NameIdParam(it.realname,it.uid.toString()))
                    }
                }else{
                    ls.add(NameIdParam(it.realname,it.uid.toString()))
                }
            }
        }
        member.postValue(ls)

    }

    fun onClickDaodian(view:View){
        memberInit()
        var content = view.context
        if (content is AppCompatActivity) {
            if (dialog == null) {
                dialog = PopDialog()
                dialog!!.listener = this
            }
            dialog?.show(content.supportFragmentManager, "pop")
        }
    }

    override var list: MutableLiveData<List<NameIdParam>>
        get(){
            return member
        }
        set(value) { list = value}
    override var dialogType: MutableLiveData<String>
        get() {
            return MutableLiveData("list")
        }
        set(value) {dialogType = value}
    override var dialogTitle: MutableLiveData<String>
        get() {
            return MutableLiveData("选择移交的用户")
        }
        set(value) {
            dialogTitle = value
        }

    override fun onClickItem(view: View, param: NameIdParam) {
        member.value?.apply {
            for (item in this) {
                item.IsSelect = param.id == item.id
            }
        }
        memberName.set(param.name)
        memberId = param.id.toString()
        if(dialog!=null){
            dialog?.dismiss()
        }
        var level = 0
        for(n in customerlevel!!){
            if(n.ikey.equals("N") || n.ikey.equals("n"))
                level = n.id
        }
        var method: () -> Unit = {
            LiveEventBus.get().with("clueupdatge").postValue("")
            MyToast("分配成功")
            myFinish()
        }

        clueDetailsRepository.getHandover("archive.index", clueDetails.get()?.tid.toString(),memberId,level.toString(),"",method)
    }

    override fun onDialogSubmit(view: View, param: String) {

    }
}